package org.hank.compose_yyzs.ui.screen

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SheetState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.Navigation
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator
import com.ramcosta.composedestinations.navigation.EmptyDestinationsNavigator
import com.ramcosta.composedestinations.spec.DestinationStyle
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.hank.compose_yyzs.R
import org.hank.compose_yyzs.bean.BuildingBean
import org.hank.compose_yyzs.constants.Constants
import org.hank.compose_yyzs.ui.paging.RefreshList
import org.hank.compose_yyzs.ui.theme.AppTheme
import org.hank.compose_yyzs.ui.theme.cyan4
import org.hank.compose_yyzs.ui.widget.EmptyCompose
import org.hank.compose_yyzs.ui.widget.clickNoWave
import org.hank.compose_yyzs.ui.widget.dialog.BottomListSelectDialog
import org.hank.compose_yyzs.utils.getString
import org.hank.compose_yyzs.utils.getStringArray
import org.hank.compose_yyzs.utils.getStringArrayGlobal
import org.hank.compose_yyzs.viewmodel.BuildingViewModel
import kotlin.reflect.typeOf

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 *@auth: Hank
 *邮箱: cs16xiaoc1@163.com
 *创建时间: 2023/11/17 14:55
 *描述:
 */
data class BuildScreenIntent(var projectId: Int)

/**
 * @param  buildScreenIntent
 * 这个参数没有使用是因为在viewModel中使用了。注解路由框架默认将projectId注入到了SaveInstance，在viewModel中使用
 */
@Destination(
    navArgsDelegate = BuildScreenIntent::class
)
@Composable
fun BuildingScreen(navigator: DestinationsNavigator, buildScreenIntent: BuildScreenIntent) {

    var viewModel: BuildingViewModel = hiltViewModel()
    var pager = viewModel.pager.collectAsLazyPagingItems()
    var currentStage = viewModel.currentStage.collectAsStateWithLifecycle()
    var state = rememberLazyListState()
    var refreshing = viewModel.isRefresh.collectAsStateWithLifecycle()
    var showModalState = remember { mutableStateOf(false) }
    var scope = rememberCoroutineScope()

    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        BuildingTopBar(navigator, showModalState) {
            navigator.popBackStack()
        }
        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = viewModel.projectName.collectAsStateWithLifecycle().value,
            modifier = Modifier.padding(start = 16.dp, top = 8.dp),
            style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold)
        )
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            if (pager!!.itemCount == 0 && pager.loadState.append !is LoadState.Error)
                EmptyCompose()

            RefreshList(
                lazyPagingItems = pager,
                isRefreshing = refreshing.value,
                onRefresh = {
                    scope.launch {
                        viewModel.isRefresh.emit(true)
                    }
                },
                listState = state
            ) {
                items(count = pager.itemCount, key = pager.itemKey { it.id }) { itemIndex ->
                    if (itemIndex == 0) {
                        Spacer(modifier = Modifier.height(1.dp))
                    }
                    ListItemBuilding(buildingBean = pager[itemIndex]!!) {

                    }
                }
            }
        }

        BottomListSelectDialog(
            title = getString(resourceId = R.string.task_detail_stage_title),
            state = showModalState,
            listItems = getStringArray(resourceId = R.array.home_stage).toMutableList(),
            navigator = navigator,
            defaultSelect = currentStage.value,
            onItemClick = {
                scope.launch {
                    showModalState.value = false
                    MMKV.defaultMMKV().putInt(Constants.CURRENT_STAGE, it)
                    viewModel.currentStageName.emit(getStringArrayGlobal(resourceId = R.array.home_stage_show)[it])
                    viewModel.isRefresh.emit(true)
                }
            }
        ) {
            scope.launch {
                showModalState.value = false
            }
        }
    }
}

@Composable
fun ListItemBuilding(buildingBean: BuildingBean, onItemClick: () -> Unit) {
    Surface(
        shape = MaterialTheme.shapes.medium,
        shadowElevation = 2.dp,
        color = AppTheme.colors.mainColor
    ) {
        Row(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp), verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(
                    id = when (buildingBean.status) {
                        0 -> {
                            R.mipmap.ic_status_waiting
                        }

                        1 -> {
                            R.mipmap.ic_status_progress
                        }

                        2 -> {
                            R.mipmap.ic_status_complete
                        }

                        else -> {
                            R.mipmap.ic_status_waiting
                        }
                    }
                ), contentDescription = ""
            )
            Text(text = buildingBean.blockName, modifier = Modifier.padding(start = 4.dp))
            Spacer(modifier = Modifier.weight(1f))
            Column {
                Text(
                    text = "${getString(resourceId = R.string.building_measure_num)}(${
                        String.format(
                            getString(resourceId = R.string.building_measure_num_formate),
                            buildingBean.stageData?.finishRoomCount ?: 0,
                            buildingBean.stageData?.totalRoomCount ?: 0
                        )
                    })"
                )
                val color = AppTheme.colors.themeUi
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .height(intrinsicSize = IntrinsicSize.Max)
                        .background(
                            shape = MaterialTheme.shapes.large,
                            color = AppTheme.colors.secondBtnBg
                        )
                        .drawBehind {
                            drawRoundRect(
                                color = color,
                                size = Size(
                                    size.width * ((buildingBean.stageData?.finishRoomCount
                                        ?: 1f).toFloat() /
                                            (buildingBean.stageData?.totalRoomCount
                                                ?: 1f).toFloat()),
                                    size.height
                                ),
                                cornerRadius = CornerRadius(24.dp.toPx())
                            )
                        }
                ) {
                    Text(
                        text = "",
                        style = MaterialTheme.typography.labelSmall.copy(fontSize = 5.sp)
                    )
                }
            }
            Spacer(modifier = Modifier.width(4.dp))
            Image(painter = painterResource(id = R.mipmap.ic_into_grey), contentDescription = "")
        }
    }
}

@Composable
fun BuildingTopBar(
    navigator: DestinationsNavigator,
    showModalState: MutableState<Boolean>,
    onBackClick: () -> Unit
) {
    val viewModel: BuildingViewModel = hiltViewModel()
    val currentStageName = viewModel.currentStageName.collectAsStateWithLifecycle()
    var scope = rememberCoroutineScope()

    LaunchedEffect(key1 = null) {
        var stage = MMKV.defaultMMKV().getInt(Constants.CURRENT_STAGE, 0)
        viewModel.currentStageName.emit(getStringArrayGlobal(resourceId = R.array.home_stage_show)[stage])
    }

    Surface(
        color = AppTheme.colors.mainColor,
        shadowElevation = 4.dp
    ) {
        Box(modifier = Modifier.fillMaxWidth()) {
            Image(
                painter = painterResource(id = R.mipmap.ic_return_black),
                contentDescription = "",
                modifier = Modifier
                    .align(Alignment.CenterStart)
                    .padding(16.dp)
                    .clickNoWave {
                        onBackClick.invoke()
                    }
            )
            Text(
                text = getString(resourceId = R.string.building_title),
                style = MaterialTheme.typography.titleLarge,
                modifier = Modifier
                    .align(Alignment.CenterStart)
                    .padding(top = 16.dp, bottom = 16.dp, start = 60.dp)
            )
            Surface(
                modifier = Modifier
                    .align(Alignment.CenterEnd)
                    .padding(end = 16.dp)
                    .clickNoWave {
                        scope.launch {
                            showModalState.value = true
                        }
                    },
                shape = MaterialTheme.shapes.extraLarge,
                color = AppTheme.colors.secondBtnBg
            ) {
                Row(
                    modifier = Modifier.padding(
                        start = 16.dp,
                        end = 16.dp,
                        top = 4.dp,
                        bottom = 4.dp
                    )
                ) {
                    Text(text = currentStageName.value)
                    Spacer(modifier = Modifier.width(4.dp))
                    Image(
                        painter = painterResource(id = R.mipmap.ic_pick), contentDescription = "",
                        modifier = Modifier.align(Alignment.CenterVertically)
                    )
                }
            }

        }
    }
}